import Cookies from 'js-cookie';
import { ElMessage } from 'element-plus';
import { i18n } from '@core/i18n';
import EnvConfig from '@core/utils/EnvConfig';
import HistoryHelper from '@core/utils/HistoryHelper';
import Sso from './Sso';

const OssTokenCookieNames = {
  Production: 'ctcns-sso-token',
  Staging: 'ctcns-staging-sso-token',
  Development: 'ctcns-dev-sso-token',
};

/**
 * 跨 app 管理 userToken
 *
 * Login 之后得到 platform-sso 服务返回的 token 字符串，存放到 cookie 中来跨 app 使用。Cookie 时效为 7 天。
 */
export default class Session {
  static login = async (loginForm: { username: string, password: string }) => {
    const authToken = await Sso.login(loginForm);
    if (!authToken) {
      const errorMessage = i18n.global.t('common.loginServiceError');
      ElMessage.error(errorMessage);
      throw new ReferenceError(errorMessage);
    }
    Session.setAuthToken(authToken);
  };

  static verify = Sso.verify;

  static logout = async () => {
    await Sso.logout();
    Session.deleteAuthToken();
    HistoryHelper.replaceToLogin();
  };

  static setAuthToken = (authToken: string) => {
    if (!authToken) {
      return;
    }
    Cookies.set(Session.getCookieNameOfToken(), authToken, { expires: 7 });
  };

  static getAuthToken = () => {
    return Cookies.get(Session.getCookieNameOfToken()) || undefined;
  };

  static deleteAuthToken = () => {
    Cookies.remove(Session.getCookieNameOfToken());
  };

  static getCookieNameOfToken = () => {
    if (EnvConfig.isConnectToProduction()) {
      return OssTokenCookieNames.Production;
    }
    if (EnvConfig.isConnectToStaging()) {
      return OssTokenCookieNames.Staging;
    }
    if (EnvConfig.isConnectToDevelopment() || EnvConfig.isConnectToLocal()) {
      return OssTokenCookieNames.Development;
    }
    throw new Error(`未注册的运行环境，无法获取对应的 cookie name。 API_ENV: ${EnvConfig.apiEnv}`);
  };

  // TODO: 接入 platform-sso fetchMe api 并作缓存
  static getUsername = () => 'whoami@whereamifrom';
}
